/**
 * Copyright (c) 2018 湖南牛数 All rights reserved.
 * <p>
 * https://www.dshubs.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.dshubs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.dshubs.commons.mybatis.enums.DelFlagEnum;
import io.dshubs.commons.mybatis.service.impl.BaseServiceImpl;
import io.dshubs.commons.security.user.SecurityUser;
import io.dshubs.commons.security.user.UserDetail;
import io.dshubs.commons.tools.constant.Constant;
import io.dshubs.commons.tools.enums.DeleteEnum;
import io.dshubs.commons.tools.enums.SuperAdminEnum;
import io.dshubs.commons.tools.enums.SuperTenantEnum;
import io.dshubs.commons.tools.enums.SysTenantEnum;
import io.dshubs.commons.tools.exception.ErrorCode;
import io.dshubs.commons.tools.exception.RenException;
import io.dshubs.commons.tools.page.PageData;
import io.dshubs.commons.tools.utils.ConvertUtils;
import io.dshubs.dao.SysTenantDao;
import io.dshubs.dao.SysUserDao;
import io.dshubs.dto.SysTenantDTO;
import io.dshubs.entity.SysTenantEntity;
import io.dshubs.entity.SysUserEntity;
import io.dshubs.service.SysRoleUserService;
import io.dshubs.service.SysTenantService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


/**
 * 租户管理
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service
public class SysTenantServiceImpl extends BaseServiceImpl<SysTenantDao, SysTenantEntity> implements SysTenantService {
    @Autowired
    private SysRoleUserService sysRoleUserService;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public PageData<SysTenantDTO> page(Map<String, Object> params) {
        //转换成like
        paramsToLike(params, "tenantName");

        //分页
        IPage<SysTenantEntity> page = getPage(params, "t1.creator", false);

        //查询
        List<SysTenantEntity> list = baseDao.getList(params);

        return getPageData(list, page.getTotal(), SysTenantDTO.class);
    }

    @Override
    public SysTenantDTO get(Long id) {
        SysTenantEntity entity = baseDao.getById(id);

        return ConvertUtils.sourceToTarget(entity, SysTenantDTO.class);
    }

    @Override
    public SysTenantDTO getTenantCode(Long tenantCode) {
        SysTenantEntity entity = baseDao.getTenantCode(tenantCode);

        return ConvertUtils.sourceToTarget(entity, SysTenantDTO.class);
    }

    @Override
    public List<SysTenantEntity> listAll() {
        QueryWrapper<SysTenantEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("creator");
        UserDetail user = SecurityUser.getUser();
        if(user.getSuperAdmin() != SuperAdminEnum.YES.value()){
            wrapper.eq("tenant_code",user.getTenantCode());

        }
        wrapper.eq(Constant.DEL_FLAG, DelFlagEnum.NORMAL.value());
        return this.baseDao.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysTenantDTO dto) {
        SysTenantEntity entity = ConvertUtils.sourceToTarget(dto, SysTenantEntity.class);

        //账号已存在
        SysUserEntity userEntity = sysUserDao.getByUsername(dto.getUsername());
        if (userEntity != null) {
            throw new RenException(ErrorCode.ACCOUNT_EXIST);
        }

        //保存用户
        userEntity = ConvertUtils.sourceToTarget(dto, SysUserEntity.class);
        userEntity.setPassword(passwordEncoder.encode(dto.getPassword()));
        userEntity.setSuperTenant(SuperTenantEnum.YES.value());
        userEntity.setSuperAdmin(SuperAdminEnum.NO.value());
        userEntity.setGender(2);
        sysUserDao.insert(userEntity);

        //保存角色用户关系
        sysRoleUserService.saveOrUpdate(userEntity.getId(), dto.getRoleIdList());

        //保存租户
        entity.setUserId(userEntity.getId());
        entity.setDelFlag(DeleteEnum.NO.value());
        entity.setSysTenant(SysTenantEnum.NO.value());
        insert(entity);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysTenantDTO dto) {
        //更新租户
        SysTenantEntity entity = ConvertUtils.sourceToTarget(dto, SysTenantEntity.class);
        updateById(entity);

        //查询租户用户ID
        Long userId = baseDao.selectById(entity.getId()).getUserId();

        //更新用户
        SysUserEntity userEntity = ConvertUtils.sourceToTarget(dto, SysUserEntity.class);
        userEntity.setId(userId);
        //密码加密
        if (StringUtils.isBlank(dto.getPassword())) {
            userEntity.setPassword(null);
        } else {
            String password = passwordEncoder.encode(dto.getPassword());
            userEntity.setPassword(password);
        }
        sysUserDao.updateById(userEntity);

        // 2021-08-24 begin tan 租户禁用之后，该租户下的用户也禁止
        List<SysUserEntity> selectList = sysUserDao.selectList(new QueryWrapper<SysUserEntity>().eq("tenant_code", entity.getTenantCode()));
        if(CollectionUtils.isNotEmpty(selectList)) {
            selectList.forEach(i->{
                i.setStatus(dto.getStatus());
                sysUserDao.updateById(i);
            });
        }
        // 2021-08-24 end tan 租户禁用之后，该租户下的用户也禁止

        //更新角色用户关系
        sysRoleUserService.saveOrUpdate(userEntity.getId(), dto.getRoleIdList());
    }

    @Override
    public void delete(Long[] ids) {
        baseDao.deleteBatch(ids);
    }
}
